<template>
	<view class="content">

		<view class="box">
			<checkbox-group class="check-box-all" @change="selectAllChange">
				<label>
					<checkbox class="check-box" value="all" :checked="isAllChecked=='true'?true:false" backgroundColor="#F7F8FA"
						activeBackgroundColor="#2979ff" activeBorderColor="#" iconColor="#FFFFFF" />
				</label>
			</checkbox-group>
			<uni-collapse ref="collapse">
				<uni-collapse-item class="word-title" :title="'未分组 (' + selectNum + '/' + student.length + ')'"
					:open="true" title-border="none">
					<view class="list">
						<checkbox-group @change="checkboxStudentChange">
							<label class="item" v-for="(item, index) in student" :key="index">
								<!-- {{checkedList}}
						{{item.id}} -->
								<checkbox class="check-box" :checked="checkedList.includes(String(item.id))"
									:value="String(item.id)" backgroundColor="#F7F8FA" activeBackgroundColor="#2979ff"
									activeBorderColor="#" iconColor="#FFFFFF" />
								<view class="name">
									{{item.nickname}}
								</view>
							</label>
						</checkbox-group>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>

		<view class="footer">
			<view class="footer-left">
				<checkbox-group @change="selectAllChange">
					<label>
						<checkbox class="check-box" value="all" :checked="isAllChecked=='true'?true:false"
							backgroundColor="#F7F8FA" activeBackgroundColor="#2979ff" activeBorderColor="#"
							iconColor="#FFFFFF" />

					</label>
				</checkbox-group>
				<view class="footer-text" @tap="selectAllChange">
					全选
				</view>
			</view>
			<view class="footer-next" @tap="handleClickConfirm">
				确 认
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isAllChecked: false,
				selectNum: 0,
				student: [],
				checkedList: [],
				xuanzhede_bj: [],
				cid: '',
				id: '',
			}
		},
		onLoad(option) {
			this.isAllChecked = option.isAllChecked
			console.log("===this.isAllChecked ",this.isAllChecked )
			// var  xzad=		
			this.xuanzhede_bj = uni.getStorageSync('xuanzhede_bj')?uni.getStorageSync('xuanzhede_bj'): []; ///从本地缓存中同步移除指定key的数据
			// 	this.checkedList=this.xuanzhede_bj.uid			

			// 	//console.log(this.checkedList,9999)
			this.id = parseInt(option.id)
			this.cid = option.grade_id
			// //console.log(this.cid, 'this.cid')
			this.banji()
			console.log("===this.isAllChecked ",this.isAllChecked )
		},
		methods: {
			totalSum(array, computedField) {
				//console.log(array, '.....')
				//console.log(computedField, '.....')
				if (!array || array.length === 0) {
					return 0
				} else {
					return array.reduce((value, item) => value + +item[computedField], 0)
				}
			},
			banji() {
				var that = this
				that.alarms = []
				var data = {
					id: that.id,
					page: that.page,
					pageSize: that.pageSize,
				}
				// that.$get('grade/index',data).then(res => {
				that.$get('grade/getStudent?id=' + data.id).then(res => {
					if (res.code != 0) {

						that.student = res.data


						// 后台返回的数组
						that.student.forEach((item, index) => {
							//console.log(that.isAllChecked)
							if (that.isAllChecked == 'true') {
								item.isChecked = true;
							} else {
								item.isChecked = false;
							}
							if (item.isChecked == true) {
								let itemVal = String(item.id)
								//console.log('zhe', itemVal)
								//console.log(itemVal, "1111")
								that.checkedList.push(itemVal);
								this.selectNum = this.student.length;
							} else {
								that.xuanzhede_bj.forEach((item,index)=>{
									let sfig = item.uid
									this.selectNum = sfig.length;
									sfig.forEach((item, index) => {
										let itemVal = String(item)
										that.checkedList.push(item);
									})
								})
							}

						})
						let quocng = this.unique1(that.checkedList)
						// that.alarms.push(quocng);
						let sig = {
							'cid': this.cid,
							'id':this.id,
							'uid': quocng
						}
						
						this.setbanjiStorge(sig)

					} else {


						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}


				})

			},
			unique1(arr) {
				var hash = [];
				for (var i = 0; i < arr.length; i++) {
					if (hash.indexOf(arr[i]) == -1) {
						hash.push(arr[i]);
					}
				}
				return hash;
			},
			/** 数组去重
			 * 思路：利用数组原型对象上的 filter 和 includes 方法
			 * @param arr 需要去重的数组
			 * @param t 根据 t 字段(指定)进行去重
			 * @returns {*[]} 已去重后的数据
			 */
			deduplicate(arr, t = "") {
				//console.log(arr)
				let newArr = []
				// 有指定字段
				if (t) {
					newArr = arr.filter(function(item) {
						//console.log(newArr.includes(item[t]))
						return newArr.includes(item[t]) ? "" : newArr.push(item[t])
					})
				}
				// 无指定字段
				else {
					newArr = arr.filter(function(item) {
						//console.log(item)
						return newArr.includes(item) ? "" : newArr.push(item)
					})
				}
				return newArr
			},
			/** 数组去重结束**/
			// 全选
			selectAllChange(e) {
				this.alarms = []
				let chooseItem = e.detail.value;
				console.log(chooseItem)
				// 全选
				if (chooseItem[0] == 'all') {
					this.isAllChecked = 'true';
					this.selectNum = this.student.length;
					this.student.forEach((item, index) => {
						let itemVal = String(item.id)
						if (!this.checkedList.includes(itemVal)) {
							this.checkedList.push(itemVal);
						}
					})
					//console.log(this.student, '111')

					var ssd = this.checkedList;

					this.alarms = ssd;
					let sig = {
						'cid': this.cid,
						'id':this.id,
						'uid': this.alarms
					}
					
					this.setbanjiStorge(sig);
				} else {
					// 取消全选
					//console.log(chooseItem, 'quxiaoid')
					this.isAllChecked = 'false';
					this.checkedList = [];
					this.selectNum = 0;
					let sig = {
						'cid': this.cid,
						'id':this.id,
						'uid':""
					}
					this.setbanjiStorge(sig);
				}


				// if (this.isAllChecked) {
				// 	this.checkedList = [];
				// 	this.isAllChecked = false;
				// 	this.selectNum = 0;
				// } else {
				// 	this.checkedList = this.student.slice();
				// 	this.isAllChecked = true;
				// 	// //console.log(e.target.value)

				// 	this.onleft()

				// }
			},

			setbanjiStorge(sig){
				//console.log(  "===sig",sig)
				if (sig.uid != '' && sig.uid != ' ') {
					//console.log("==this.xuanzhede_bj",this.xuanzhede_bj)
					let index = this.xuanzhede_bj.findIndex(item => item.id === sig.id);
					//console.log("===index",index)
					// 根据查找结果进行处理
					if (index !== -1) {
						// 如果找到了，替换该对象（或者只更新其属性，如果需要的话）
						// 这里假设我们要用一个新的对象来替换它
						//console.log("==这里假设我们要用一个新的对象来替换它")
						this.xuanzhede_bj.map((item,index)=>{
							//console.log("====item.cid == sig.cid",item.cid == sig.cid)
							if(item.id == sig.id){
								this.xuanzhede_bj.splice(index,1,sig)
							}
						})
					} else {
						//console.log("===没有，进行添加")
						// 如果没有找到，将新对象添加到数组中
						this.xuanzhede_bj.push({ ...sig }); // 使用展开运算符复制pids对象的所有属性
					}
				}else{
					let index = this.xuanzhede_bj.findIndex(item => item.cid === sig.cid);
					if (index !== -1) {
						// 如果找到了，替换该对象（或者只更新其属性，如果需要的话）
						// 这里假设我们要用一个新的对象来替换它
						//console.log("==这里假设我们要用一个新的对象来替换它")
						this.xuanzhede_bj.map((item,index)=>{
							//console.log("====item.cid == sig.cid",item.cid == sig.cid)
							if(item.id == sig.id){
								this.xuanzhede_bj.splice(index,1)
							}
						})
					}
					//console.log("===index",index)
				}
			},
			// 单个勾选
			checkboxStudentChange(e) {
				this.alarms = []
				this.checkedList = e.detail.value;
				// 如果选择的数组中有值，并且长度等于列表的长度，就是全选
				if (this.checkedList.length > 0 && this.checkedList.length == this.student.length) {
					this.isAllChecked = true;
				} else {
					this.isAllChecked = false;
				}

				if (this.checkedList.length != 0) {
					this.checkedList.forEach((item, index) => {
						let itemVal = String(item)
						this.alarms.push(itemVal);
					})
					this.selectNum = e.target.value.length;
					let sig = {
						'cid': this.cid,
						'id':this.id,
						'uid': this.alarms
					}
					this.setbanjiStorge(sig);

				} else {
					this.selectNum = e.target.value.length;
					let sig = {
						'cid': this.cid,
						'id':this.id,
						'uid':""
					}
					this.setbanjiStorge(sig);
				}



			},
			goBack() {
			      // 返回上一页
			      uni.navigateBack({
			        delta: 1 // 默认值是1，表示返回的页面层数
			      });
			    },
			handleClickConfirm() {
				uni.setStorageSync('xuanzhede_bj',this.xuanzhede_bj);
				this.goBack()
			}
		}
	}
</script>

<style scoped>
	.content {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.box {
		width: 686rpx;
		border-radius: 24rpx;
		padding-left: 48rpx;
		box-sizing: border-box;
		background-color: #FFFFFF;
		display: flex;
		align-items: flex-start;
		position: relative;
	}

	.check-box-all {
		margin-top: 20rpx;
	}

	.first {
		display: flex;
		align-items: center;
		position: relative;
	}

	.title {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #222222;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
		flex: 1;
	}

	.first::after {
		content: '';
		width: 10rpx;
		height: 18rpx;
		background-image: url(@/static/arrow_icon.png);
		position: absolute;
		top: 50%;
		right: 0;
		transform: translateY(-50%) rotate(0deg);
		transition: all 0.2s ease;
	}

	.expand::after {
		content: '';
		width: 10rpx;
		height: 18rpx;
		background-image: url(@/static/arrow_icon.png);
		position: absolute;
		top: 50%;
		right: 0;
		transform: translateY(-50%) rotate(90deg);
		transition: all 0.2s ease;
	}

	.list {
		padding-left: 42rpx;
	}

	.item {
		display: flex;
		align-items: center;
		padding-bottom: 36rpx;
	}

	.name {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #222222;
		line-height: 40rpx;
		font-style: normal;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 999;
		width: calc(100vw - 52rpx);
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding:26rpx 32rpx;
	}

	.footer-left {
		position: relative;
		display: flex;
		align-items: center;
	}

	.footer-text {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
		font-style: normal;
	}

	.footer-next {
		width: 240rpx;
		height: 88rpx;
		border-radius: 45rpx;
		color: #FFFFFF;
		font-size: 30rpx;
		font-family: PingFangSC-Medium;
		font-weight: bold;
		text-align: center;
		line-height: 86rpx;
		background: #2979FF;
		box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.5), 0rpx 8rpx 12rpx 0rpx rgba(41, 121, 255, 0.5);
	}
</style>